package com.app.controller;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.app.common.RedisConstant;
import com.app.common.TotalConfig;
import com.app.model.SysCategory;
import com.app.service.ISysCategoryService;
import com.app.service.RedisService;
import com.app.util.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 * 公用数据配置	 前端控制器
 * </p>
 *
 * @author yoominic
 * @since 2023-12-05
 */
@Api(tags = "admin公用数据配置接口")
@RestController
@RequestMapping("/sysCategory")
public class SysCategoryController {

    @Autowired
    private ISysCategoryService categoryService;

    @Autowired
    private RedisService redisService;




    @ApiOperation(value = "单位详情")
    @GetMapping("/getDetail")
    public Result<SysCategory> getDetail(Integer id) {
        SysCategory sysCategory = categoryService.getById(id);
        return Result.success(sysCategory);
    }


    /**
     * 列表
     *
     * @param code 代码
     * @return {@link Result}
     */
    @ApiOperation(value = "公用数据配置列表")
    @GetMapping("list")
    public Result list(@RequestParam(value = "code") String code) {
        QueryWrapper<SysCategory> sysCategoryQueryWrapper = new QueryWrapper<>();
        sysCategoryQueryWrapper.eq("code", code);
        sysCategoryQueryWrapper.ne("pid", 0);
        return Result.success(this.categoryService.list(sysCategoryQueryWrapper));
    }


    /**
     * 获取公共数据管理树
     *
     * @param pid pid
     * @return {@link Result}
     */
    @ApiOperation(value = "获取公共数据管理树")
    @GetMapping("/getPerTree")
    public Result getPerTree(@RequestParam(value = "pid",required = false) Integer pid,
                             @RequestParam(value = "keyword",required = false) String keyword) {
        QueryWrapper<SysCategory> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq(pid!=null,"pid", pid);
        queryWrapper.like(StrUtil.isNotBlank(keyword),"name", keyword);

        List<SysCategory> catModelList = categoryService.list(queryWrapper);//全查或者根据name查
        if (catModelList == null) {
            return Result.error("暂无数据");
        }
        List<SysCategory> categoryTree = categoryService.getCategoryTree(catModelList);
        return Result.success(categoryTree);
    }

    /**
     * 添加和更新配置
     *
     * @param sysCategory 系统配置
     * @return {@link Result}
     */
    @ApiOperation(value = "添加和更新配置")
    @PostMapping("/addAndUpdateCategory")
    public Result addAndUpdateCategory(@RequestBody SysCategory sysCategory) {
        if (!StpUtil.hasPermission("admin:system:category:save")) {
            return Result.error(TotalConfig.NO_PERMISSION);
        }
        Boolean result=false;
        if (sysCategory.getId() != null && sysCategory.getId() > 0) {
            sysCategory.setUpdateTime(new Date());
            result=this.categoryService.updateById(sysCategory);
        } else {
            sysCategory.setCreateTime(new Date());
            if (sysCategory.getPid() == null) {
                sysCategory.setPid(0);
            }
            result=this.categoryService.save(sysCategory);
        }
        if(result)
        {
           this.categoryService.initCategoryTree();
        }
        return Result.success(result);
    }

    /**
     * 更新状态
     *
     * @param id     id
     * @param status 状态
     * @return {@link Result}<{@link Object}>
     */
    @ApiOperation(value = "根据公用数据配置表id更新启用禁用状态")
    @GetMapping("/updateCategoryStatus")//修改状态
    public Result updateStatus(@RequestParam("id") Integer id,
                               @RequestParam("status") Integer status) {
        if (!StpUtil.hasPermission("admin:system:category:status")) {
            return Result.error(TotalConfig.NO_PERMISSION);
        }
        SysCategory model = new SysCategory();
        model.setId(id);
        model.setStatus(status);
        categoryService.updateById(model);
        this.categoryService.initCategoryTree();
        return Result.success("修改成功");
    }

    /**
     * 删除配置
     *
     * @param id id
     * @return {@link Result}<{@link Object}>
     */
    @ApiOperation(value = "删除配置")
    @GetMapping("/deleteCategory")
    public Result deleteCategory(@RequestParam("id") Integer id) {
        if (!StpUtil.hasPermission("admin:system:category:delete")) {
            return Result.error(TotalConfig.NO_PERMISSION);
        }
        SysCategory model = categoryService.getById(id);
        if (model == null) {
            return Result.error("该条数据不存在");
        } else {
            if (model.getPid() == 0) {
                categoryService.removeById(model.getId());
            }
            categoryService.removeById(id);
            this.categoryService.initCategoryTree();
            return Result.success(null);
        }
    }

    /**
     * 按id获取配置
     *
     * @param id      id
     * @param request 请求
     * @return {@link Result}<{@link Object}>
     */
    @ApiOperation(value = "按id获取配置")
    @GetMapping("/getCategoryById")
    public Result<Object> getCategoryById(Integer id, HttpServletRequest request) throws JsonProcessingException {
        if (!StpUtil.hasPermission("admin:system:category:detail")) {
            return Result.error(TotalConfig.NO_PERMISSION);
        }
        Object categoryObject=this.redisService.get(RedisConstant.CATEGORY_CACHE_PREFIX);
        if(categoryObject!=null)
        {
            List<SysCategory> sysCategoryList= JSONUtil.toList(categoryObject.toString(),SysCategory.class);
            ObjectMapper mapper = new ObjectMapper();

            List<Map<String, Object>> data = mapper.readValue(JSONUtil.toJsonStr(sysCategoryList), new TypeReference<List<Map<String, Object>>>() {});

            // 构建 id 到节点的映射缓存
            Map<Integer, Map<String, Object>> idCache = buildIdCache(data);

            // 查询 pid = 29 的子数组
            List<Map<String, Object>> result = getChildrenByPid(id, idCache);
            return Result.success(result);
        }
        return Result.success(null);
    }


    // 构建 id 到节点的映射缓存
    public static Map<Integer, Map<String, Object>> buildIdCache(List<Map<String, Object>> data) {
        Map<Integer, Map<String, Object>> idCache = new HashMap<>();
        Queue<Map<String, Object>> queue = new LinkedList<>(data);
        while (!queue.isEmpty()) {
            Map<String, Object> node = queue.poll();
            idCache.put((Integer) node.get("id"), node);
            List<Map<String, Object>> children = (List<Map<String, Object>>) node.getOrDefault("child", Collections.emptyList());
            queue.addAll(children);
        }
        return idCache;
    }

    // 根据 pid 直接查询子数组
    public static List<Map<String, Object>> getChildrenByPid(int pid, Map<Integer, Map<String, Object>> idCache) {
        if (idCache.containsKey(pid)) {
            return (List<Map<String, Object>>) idCache.get(pid).getOrDefault("child", Collections.emptyList());
        }
        return Collections.emptyList();
    }


    /**
     * 按id获取配置
     *
     * @param id id
     * @return {@link Result}<{@link Object}>
     */
    @ApiOperation(value = "详情")
    @GetMapping("/details")
    public Result<Object> details(@RequestParam(value = "id") Integer id) {
        if (!StpUtil.hasPermission("admin:system:category:detail")) {
            return Result.error(TotalConfig.NO_PERMISSION);
        }

        return Result.success(this.categoryService.getById(id));
    }
}

